package com.ctg.payroll2.action.sysadmin;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Calendar;
import java.util.StringTokenizer;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.struts2.ServletActionContext;

import com.googlecode.jsonplugin.annotations.JSON;
import com.opensymphony.xwork2.ActionSupport;

/**
 * @author sami 文件上传
 */
public class FileuploadAction extends ActionSupport {

	public static final String ROOT = "upload\\";

	private boolean success;

	/**
	 * 上传文件名
	 */
	private String uploadName;

	private String resultString;
	/**
	 * File
	 */
	private File myfile;
	/**
	 * FileName
	 */
	private String myfileFileName;
	/**
	 * path
	 */
	private String path;

	private String myfileContentType;

	public String getResultString() {
		return resultString;
	}

	@JSON(serialize = false)
	public String getMyfileFileName() {
		return myfileFileName;
	}

	public void setMyfileFileName(String myfileFileName) {
		this.myfileFileName = myfileFileName;
	}

	public void setResultString(String resultString) {
		this.resultString = resultString;
	}

	@JSON(serialize = false)
	public File getMyfile() {
		return myfile;
	}

	public void setMyfile(File myfile) {
		this.myfile = myfile;
	}

	/**
	 * @return
	 */
	public String uploadFile() {
		try {
			getResponse().setCharacterEncoding("UTF-8");
			String rootPath = getSession().getServletContext().getRealPath("/");
			rootPath += ROOT;
			String sp = rootPath;
			/**
			 * 
			 */
			uploadName = createNewFileName(getMyfileFileName());
			resultString = sp.replace("\\","\\\\") + uploadName;
			mkDirectory(sp);
			upload(uploadName, sp, getMyfile());
			success = true;
		} catch (Exception e) {
			success = false;
			resultString = "请检查上传文件是否完好";
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 * @param uploadFileName
	 * @param savePath
	 * @param uploadFile
	 * @return
	 */
	public boolean upload(String uploadFileName, String savePath,
			File uploadFile) {
		boolean flag = false;
		try {
			uploadForName(uploadFileName, savePath, uploadFile);
			flag = true;
		} catch (IOException e) {
			flag = false;
			e.printStackTrace();
		}
		return flag;
	}

	/**
	 * @param uploadFileName
	 * @param savePath
	 * @param uploadFile
	 * @return
	 * @throws IOException
	 */
	public String uploadForName(String uploadFileName, String savePath,
			File uploadFile) throws IOException {
		String newFileName = uploadFileName;
		FileOutputStream fos = null;
		FileInputStream fis = null;
		try {
			fos = new FileOutputStream(savePath + newFileName);
			fis = new FileInputStream(uploadFile);
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = fis.read(buffer)) > 0) {
				fos.write(buffer, 0, len);
			}
		} catch (FileNotFoundException e) {
			throw e;
		} catch (IOException e) {
			throw e;
		} finally {
			try {
				if (fos != null) {
					fos.close();
				}
				if (fis != null) {
					fis.close();
				}
			} catch (IOException e) {
				throw e;
			}
		}
		return newFileName;
	}

	public String getMyfileContentType() {
		return myfileContentType;
	}

	public void setMyfileContentType(String myfileContentType) {
		this.myfileContentType = myfileContentType;
	}

	@JSON(serialize = false)
	public HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	/**
	 * 获得response
	 * 
	 * @return
	 */
	@JSON(serialize = false)
	public HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	/**
	 * 获得session
	 * 
	 * @return
	 */
	@JSON(serialize = false)
	public HttpSession getSession() {
		return getRequest().getSession();
	}

	/**
	 * 获得servlet上下文
	 * 
	 * @return
	 */
	@JSON(serialize = false)
	public ServletContext getServletContext() {
		return ServletActionContext.getServletContext();
	}

	@JSON(serialize = false)
	public String getRealyPath(String path) {
		return getServletContext().getRealPath(path);
	}

	public static boolean mkDirectory(String path) {
		File file = null;
		try {
			file = new File(path);
			if (!file.exists()) {
				return file.mkdirs();
			}
		} catch (RuntimeException e) {
			e.printStackTrace();
		} finally {
			file = null;
		}
		return false;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) throws UnsupportedEncodingException {
		this.path = URLDecoder.decode(path, "UTF-8");
	}

	public static String getROOT() {
		return ROOT;
	}

	public String getUploadName() {
		return uploadName;
	}

	public void setUploadName(String uploadName) {
		this.uploadName = uploadName;
	}

	public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	public String createNewFileName(String fileName) {
		Calendar c = Calendar.getInstance();
		int yyyy = c.get(Calendar.YEAR);
		int mm = c.get(Calendar.MONTH) + 1;
		int dd = c.get(Calendar.DAY_OF_MONTH);
		String nowdate = yyyy + "" + mm + "" + dd + "";
		String filesuffix = null;
		StringTokenizer fx = new StringTokenizer(fileName, ".");
		while (fx.hasMoreTokens()) {
			filesuffix = fx.nextToken();
		}
		String fileType = "." + filesuffix;
		String newFileName = nowdate
				+ RandomStringUtils.randomAlphabetic(5).toUpperCase()
				+ fileType;
		return newFileName;
	}
}